﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Collections.ObjectModel;
using System.Xml;

namespace Ridofy.LastFm
{
    public class LastFmRssClient : ILastFmRssClient
    {
        public Track[]  RecentTracks(string user)
        {
            string url = string.Format("http://ws.audioscrobbler.com/2.0/user/{0}/recenttracks.rss",user);
            return ParseLastFmRss(url);            
        }

        public Track[] LovedTracks(string user)
        {
            string url = string.Format("http://ws.audioscrobbler.com/2.0/user/{0}/lovedtracks.rss", user);
            return ParseLastFmRss(url);
        }

        private Track[] ParseLastFmRss(string url)
        {
            using (XmlReader reader = XmlReader.Create(url))
            {
                SyndicationFeed feed = SyndicationFeed.Load(reader);
                var items = from t in feed.Items
                            select CreateTrack(t.Title.Text);
                return items.ToArray<Track>();
            }
        }

        Track CreateTrack(string s)
        {
            Console.WriteLine(s);
            int pos = s.IndexOf("–", StringComparison.InvariantCultureIgnoreCase);
            if (pos < 0) return new Track { Title = s };
            return new Track
            {
                Artist = new Artist { Name = s.Substring(0, pos-1) },
                Title = s.Substring(pos+2, s.Length - pos -2)
            };
        }
    }
}
